function saveTimes()

    local MapName = game.GetMap()
    local FileName = "SpaceRace/BestTimes/"..MapName.."_Times.txt"
    
    file.Write(FileName, util.TableToKeyValues(TimesTable))
    print("=============Times file saved=============")
    print("=============="..table.Count(TimesTable).." times saved==============")
  
end

function updateTime(ply, newtime)

    print("SR Added time to file: "..ply:Nick().." - "..newtime)
    local ID = string.lower(string.Replace(ply:SteamID(),":","_"))
    TimesTable[ID] = newtime

    --table.SortByMember(TimesTable, "Best", function(a, b) return a > b end)
    table.sort(TimesTable, function(a, b) return a > b end)
 
    saveTimes()
 
    PrintTable(TimesTable);

end

function send_times_table( ply )

    umsg.Start( "SendTimesTable" , ply)
        umsg.Long( table.Count(TimesTable) ) 

        for k, v in pairs(TimesTable) do
            umsg.String( k )
            umsg.Float( v )
        end
    umsg.End()
end

function started_race( ply )
    if ply:Team() == TEAM_ENTRANT then
        
        ply:EmitSound("ambient/alarms/klaxon1.wav", 500, 100)
    
        ply.RaceStart = SysTime()
        ply:SetNetworkedFloat("StartTime",ply.RaceStart)
        ply:SetTeam( TEAM_RACER )
        --SetPlayerLoadout( ply )
        ply:StripWeapons()
        
        ply.checkpoints = 0
        ply.lastCheck = 0
    end
end

function checkpoint(ply, checkpoint_num)
    if GetConVarNumber("sr_debug") == 1 then print("SR checkpoint_num: "..tostring(checkpoint_num)) end
    if ply.lastCheck == nil then ply.lastCheck = 0 end
    if ply.checkpoints == nil then ply.checkpoints = 0 end
    if checkpoint_num > ply.lastCheck then
    
        ply:EmitSound("buttons/combine_button1.wav", 500, 255)
        ply:EmitSound("buttons/button17.wav", 500, 80)
    
        ply.lastCheck = checkpoint_num
        ply.checkpoints = ply.checkpoints + 1

        checkpoints = GetGlobalInt ( "checkpoints" )
        local SplitTime = string.format('%1.3f',SysTime() - ply.RaceStart)
        showMessage(ply, "Checkpoint "..checkpoint_num.." of "..checkpoints..", Split Time: "..SplitTime.." seconds")
    end
end

function finished_race( ply )
    
    if ply:Team() == TEAM_RACER then
        local Map = game.GetMap()
        ply.RaceFinish = SysTime()
        ply.RaceTime = ply.RaceFinish - ply.RaceStart
        --ply.BestTime = tonumber(ply:GetPData(Map.."_BestTime",0))
        local ID = string.lower(string.Replace(ply:SteamID(),":","_"))
        ply.BestTime = TimesTable[ID] or 0
        
        checkpoints = tonumber(GetGlobalInt( "checkpoints" ))

        --local message = ply:Nick() .. " finished the race in " .. string.format('%1.3f',tonumber(ply.RaceTime) .. " seconds")
        if GetConVarNumber("sr_debug") == 1 then print("Time: "..ply.RaceTime) end
        local formattedTime = string.format('%1.3f',ply.RaceTime)
        
        local message = ply:Nick() .. " finished the race in " .. formattedTime .. " seconds"
        
        if ply.checkpoints != checkpoints then
            message = ply:Nick() .. " did "..ply.checkpoints.." of "..checkpoints.." checkpoints."
        else

            if ply.RaceTime < ply.BestTime || ply.BestTime <= 0 then
    
                ply.BestTime = tonumber(ply.RaceTime)
                --ply:SetPData(Map.."_BestTime", tonumber(ply.RaceTime ))
                ply:SetNWFloat("BestTime", tonumber(ply.RaceTime ))
                updateTime(ply, ply.BestTime) --store this in our Best Times table
                message = ply:Nick() .. " set a new personal best of " .. formattedTime .. " seconds"
            end
            print(message)
            
            for k,v in pairs(player.GetAll()) do
                v:PrintMessage( HUD_PRINTTALK , "[SpaceRace] " .. message)
            end
        end
        showMessage(ply, message )
        join_team_spectator( ply )
    end
end

function get_best_time( ply )
 
    --return ply.BestTime
    local ID = string.lower(string.Replace(ply:SteamID(),":","_"))
    return TimesTable[ID] or 0
end

function show_best_time( ply )

    print("show_best_time ply.BestTime: "..ply:Nick().." - "..ply.BestTime)
    print("show_best_time get_best_time(): "..ply:Nick().." - "..get_best_time(ply))
    print("show_best_time sr_debug: "..GetConVarNumber("sr_debug") == 1)
end

function clear_best_time( ply )
 
    local ID = string.lower(string.Replace(ply:SteamID(),":","_"))
    TimesTable[ID] = 0
    saveTimes()
    
    ply.BestTime = 0
    ply:SetNetworkedFloat("BestTime", ply.BestTime )
    
    showMessage(ply, ply:Nick() .. " cleared best time")
end